const db = require("../db/index");
// 密码加密/解密
const bcrypt = require("bcryptjs");
// 生成token
const jwt = require("jsonwebtoken");
const config = require("../config");

// 密保问题
const security = require("../assets/js/security");

// 用户注册
exports.userReg = (req, res) => {
  const sqlStr = "select * from users where student_id=?";
  const userInfo = req.body;
  db.query(sqlStr, userInfo.student_id, (err, results) => {
    if (err) return res.cc(err);
    if (results.length > 0) return res.cc("用户已存在，请更换其他用户号！");
    userInfo.password = bcrypt.hashSync(userInfo.password, 10);
    const sqlStr = "insert into users set ?";
    db.query(sqlStr, userInfo, (err, results) => {
      if (err) return res.cc(err);
      if (results.affectedRows !== 1)
        return res.cc("注册用户失败，请稍后再试！");
      res.cc("注册成功！", 0);
    });
  });
};

// 用户登录
exports.userLogin = (req, res) => {
  const userInfo = req.body;
  const sqlStr = "select * from users where student_id=?";
  db.query(sqlStr, userInfo.student_id, (err, results) => {
    if (err) return res.cc(err);
    if (results.length !== 1) return res.cc("没有该用户,登录失败!");
    //判断密码是否正确
    const compareResult = bcrypt.compareSync(
      userInfo.password,
      results[0].password
    );
    if (!compareResult) return res.cc("密码错误!");

    const user = { ...results[0], password: "", avatar: "" };
    const tokenStr = jwt.sign(user, config.jwtSecretKey, {
      expiresIn: config.expiresIn,
    });
    res.cc("登录成功!", 0, {
      student_id: results[0].student_id,
      class: results[0].class,
      grade: results[0].grade,
      avatar: results[0].avatar,
      token: "Bearer " + tokenStr,
    });
  });
};

// 重置密码
exports.resetPassword = (req, res) => {
  const userinfo = req.body;
  const sqlStr = "select * from users where student_id=?";
  db.query(sqlStr, req.body.student_id, (err, results) => {
    if (err) return res.cc(err);
    if (results.length !== 1) return res.cc("没有该用户,重置密码失败!");
    if (req.password !== req.passwordAgain)
      return res.cc("两次输入密码不一致!");
    const compareResult = bcrypt.compareSync(
      userinfo.password,
      results[0].password
    );
    if (compareResult) return res.cc("新密码不能与旧密码相同!");
    if (results[0].security !== userinfo.security)
      return res.cc("密保问题错误!");
    if (results[0].answer !== userinfo.answer) return res.cc("密保答案错误!");
    //加密密码
    userinfo.password = bcrypt.hashSync(userinfo.password, 10);
    const sqlStr = "update users set password=? where student_id=?";
    db.query(
      sqlStr,
      [userinfo.password, userinfo.student_id],
      (err, results) => {
        if (err) return res.cc(err);
        if (results.affectedRows !== 1) return res.cc("重置密码失败!");
        res.cc("重置密码成功!", 0);
      }
    );
  });
};

// 修改头像
exports.updateAvatar = (req, res) => {
  res.cc(req.body)
}